<template>
  <div id="electronicPayslipDetails">
    <div class="detailsHeader">
      <span class="title">{{routeData.subName}}</span>
      <span>{{routeData.wagesName}}</span>
      <span>{{yearMonth}}</span>
    </div>
    <div class="pageHead">
      <el-form class="listQueryForm" ref="listQuery" :model="listQuery" inline>
        <el-form-item>
          <MultipleDepartments ref="departmentsSelect" :subId="listQuery.subId" />
        </el-form-item>
        <el-form-item label="发放状态:">
          <el-select v-model="listQuery.sendStatus">
            <el-option v-for="item in sendStatusList" :key="item.dataValue" :label="item.dataName" :value="item.dataValue" />
          </el-select>
        </el-form-item>
        <el-form-item label="查看状态:">
          <el-select v-model="listQuery.isSelect">
            <el-option v-for="item in checkStatusList" :key="item.dataValue" :label="item.dataName" :value="item.dataValue" />
          </el-select>
        </el-form-item>
        <el-form-item label="确认状态:" v-if="confirmWay>1">
          <el-select v-model="listQuery.isConfirm">
            <el-option v-for="item in confirmStatusList" :key="item.dataValue" :label="item.dataName" :value="item.dataValue" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearchDetailstList(true)">查询</el-button>
        </el-form-item>
      </el-form>
      <div class="rightBox">
        <el-button @click="handleContinue()">继续发放</el-button>
        <el-button @click="handleRevoke()">撤销发放</el-button>
      </div>

    </div>
    <div class="pageMain">
      <div class="tableContent">
        <el-table :data="detailsList" height="calc(100% - 40px)" @selection-change="handleSelectChange">
          <el-table-column type="selection" :selectable="disabledCheck" align="center"></el-table-column>
          <el-table-column label="姓名" prop="realName"></el-table-column>
          <el-table-column label="工号" prop="jobNo"></el-table-column>
          <el-table-column label="部门" prop="departmentName"></el-table-column>
          <el-table-column label="岗位" prop="postName"></el-table-column>
          <el-table-column label="手机号" prop="phone"></el-table-column>
          <el-table-column label="发放时间" prop="issueTime"></el-table-column>
          <el-table-column label="发放状态" prop="sendStatus">
            <template slot-scope="scope">
              <!-- {{ getStatusText('sendStatus',scope.row) }} -->
              {{ scope.row.sendStatusDesc }}
            </template>
          </el-table-column>
          <el-table-column label="查看状态" prop="isSelect">
            <template slot-scope="scope">
              <!-- {{ getStatusText('isSelect',scope.row) }} -->
              {{scope.row.isSelectDesc}}
            </template>
          </el-table-column>
          <el-table-column label="确认状态" prop="isConfirm" v-if="confirmWay>1">
            <template slot-scope="scope">
              <!-- {{ getStatusText('isConfirm',scope.row) }} -->
              {{scope.row.isConfirmDesc}}
            </template>
          </el-table-column>
          <el-table-column label="反馈明细" prop="feedback"></el-table-column>
          <el-table-column label="操作" width="150">
            <template slot-scope="scope">
              <el-link :underline="false" type="primary" @click="handleContinue(scope.row)">发放</el-link>
              <el-link :underline="false" type="primary" style="margin-left:20px;" @click="handleRevoke(scope.row)">撤销</el-link>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination :small="true" background @size-change="(value) => handleSearchChange(value, 'pageSize')" @current-change="(value) => handleCurrentChange(value, 'pageIndex')" :current-page="listQuery.pageIndex" :page-sizes="[10, 20, 50]" :page-size="listQuery.pageSize" layout="total, sizes, prev, pager, next, jumper" :total="total" class="pagingChild"></el-pagination>
      </div>
    </div>
  </div>
</template>
<script>
import eventBus from "@/views/personnelRegulate/rewardManagement/smartSalary/salarySheet/eventBus/eventBus";
import MultipleDepartments from "@/views/personnelRegulate/rewardManagement/components/MultipleDepartments.vue";
export default {
  name: 'electronicPayslipDetails',
  components: {
    MultipleDepartments
  },
  data() {
    return {
      detailsList: [],
      confirmWay: 0,
      listQuery: {
        payslipId: 0,
        wagesId: 0,
        deptIdList: [],
        sendStatus: -1,
        isConfirm: -1,
        isSelect: -1,
        keyWord: '',
        subId: '',
        companyId: '',
        pageIndex: 1,
        pageSize: 20,
      },
      routeData: {
        wagesName: ""
      },
      total: 0,
      sendStatusList: [{ dataName: '全部', dataValue: -1 }],
      confirmStatusList: [{ dataName: '全部', dataValue: -1 }],
      checkStatusList: [{ dataName: '全部', dataValue: -1 }],
      batchList: []
    };
  },
  computed: {
    yearMonth() {
      if (JSON.stringify(this.routeData) != '{}') {
        return `${this.routeData.yearNumber}年${this.routeData.monthNumber}月`;
      }
      return '';
    }
  },
  methods: {
    handleCurrentChange(value) {
      this.listQuery.pageIndex = value;
      this.searchDetailsList();
    },
    handleSearchChange(value) {
      // 条/每页
      this.listQuery.pageSize = value;
      this.searchDetailsList();
    },
    getStatusText(prop, rowData) {
      switch (prop) {
        case 'sendStatus':
          const data = this.sendStatusList.find(e => rowData[prop] == e.value);
          return data ? data.label : '';
        case 'isSelect':
          return rowData[prop] ? '已查看' : '待查看';
        case 'isConfirm':
          return rowData[prop] ? '已确认' : '待确认';
      }
    },
    setStatusListData(prop, objData) {
      this[prop] = [];
      for (const key in objData) {
        if (Object.hasOwnProperty.call(objData, key)) {
          const element = objData[key];
          this.$set(this[prop], this[prop].length, { label: element, value: key });
        }
      }
      console.log(this[prop]);
    },
    searchSendStatusList() {
      this.$api.electronicPayslip
        .GetSendStatusList()
        .then(res => {
          // this.setStatusListData('sendStatusList', res.data.data);
          // g
          res.data.data.map(v=>{
            this.sendStatusList.push({
              dataValue: v.dataValue,
              dataName: v.dataName
            });
          });
        });
    },
    searchConfirmStatusList() {
      this.$api.electronicPayslip
        .GetConfirmStatusList()
        .then(res => {
          console.log(res, 'resres');
          if(res.data.data !== null) {
            res.data.data.map(v=>{
              this.confirmStatusList.push({
                dataValue: v.dataValue,
                dataName: v.dataName
              });
            });
          }          
        });
    },
    searchCheckStatusList() {
      this.$api.electronicPayslip
        .GetCheckStatusList()
        .then(res => {
          // this.setStatusListData('checkStatusList', res.data.data);
          // g
          res.data.data.map(v=>{
            this.checkStatusList.push({
              dataValue: v.dataValue,
              dataName: v.dataName
            });
          });
        });
    },
    searchDetailsList() {
      this.$api.electronicPayslip
        .GetIssueDetailList(this.listQuery)
        .then(res => {
          if (res.data.data) {
            this.confirmWay = res.data.data.confirmWay;
            this.detailsList = res.data.data.items;
            this.total = res.data.data.totalCount;
          } else {
            this.detailsList = [];
            this.total = 0;
          }
        });
    },

    /**
     * @description 撤销发放
     */
    revokePayslipData(payslipId, list) {
      this.$api.electronicPayslip
        .CancelIssuePayslipData(payslipId, list)
        .then(res => {
          this.$message.success(res.data.message);
          this.handleSearchDetailstList(false);
          console.log(res);
        });
    },

    /**
     * @description 进去发放页面，并传递当前页面选中参数
     */
    intoGrantPayslip(list) {
      let touserList = [];
      list.map(v=>{
        return touserList.push(v.userId);
      });
      this.$store.commit('SET_GRANT_PAYSLIP_ROUTE_DATA', {
        userList: list,
      });
      this.$router.push({
        path: '/grantPayslip',
        query: {
          month: this.routeData.monthNumber,
          year: this.routeData.yearNumber,
          wagesId: this.routeData.wagesId,
          tempId: this.routeData.salaryTempId,
          payslipId: this.routeData.id,
          confirmWay: this.confirmWay,
          pageName: "continue",
          page: "electronicPayslipDetails",
          sourceType: 2
        }
      });
    },

    /**
     * @description 判断当前行是否可勾选
     */
    disabledCheck(row) {
      if(row.isConfirm === true) {
        return false;
      }
      if (row.isConfirm) {
        return false;
      }
      return true;
    },
    // 继续发放
    handleContinue(rowData) {
      let list = [];
      if (rowData) {
        if (rowData.isConfirm) {
          return this.$message.warning('已确认员工，不可进行再次发放');
        }
        list = [rowData];
      } 
      // else {
      if (this.batchList.length == 0) {
        return this.$message.warning('请勾选要发放的数据');
      }
      list = this.batchList;
      // 发放详情列表 勾选后 存储  点击发放时缓存
      let arrList = [];
      let userIdList = [];
      list.map(v=>{
        arrList.push(v.realName);
        userIdList.push(v.userId);
      });
      let obj = {
        getArrlist: arrList
      };
      let obj1 = {
        userLists: userIdList
      };
      // console.log(list, 'list--');
      // eventBus.$emit("useIdList", userIdList);
      sessionStorage.setItem("useIdList", JSON.stringify(obj1));
      sessionStorage.setItem("arrList", JSON.stringify(obj));
      this.intoGrantPayslip(list);

    },
    // 撤销发放
    handleRevoke(rowData) {
      if (rowData) {
        if (rowData.sendStatus != 1) {
          return this.$message.warning('未发放工资条员工，不能撤销');
        }
      } else {
        if (this.batchList.length == 0) {
          return this.$message.warning('请勾选要撤销发放的数据');
        }
        if (!this.batchList.every(e => e.sendStatus == 1)) {
          return this.$message.warning('未发放工资条员工，不能撤销');
        }
      }

      //
      this.$confirm('撤销发放工资条后，员工在手机端将无法查看到，请确认是否撤销？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
      }).then(() => {
        this.revokePayslipData(this.routeData.id, rowData ? [
          {
            userId: rowData.userId,
            realName: rowData.realName,
            recordId: rowData.recordId
          }
        ] : this.batchList.map(e => {
          return {
            userId: e.userId,
            realName: e.realName,
            recordId: e.recordId
          };
        }));
      }).catch();
    },
    handleSearchDetailstList(isClean = false) {
      if (isClean) {
        this.listQuery.pageIndex = 1;
      }
      this.listQuery.deptIdList = this.$refs.departmentsSelect.getDepartments();
      this.searchDetailsList();
    },
    handleSelectChange(selection) {
      let arrList = [];
      this.batchList = selection;
      selection.map(v=>{
        arrList.push(v.realName);
      });
      let obj = {
        getArrlist: arrList
      };
      // eventBus.$emit("arrList", arrList);
      // sessionStorage.setItem("arrList", JSON.stringify(obj));
    }
  },
  mounted() {
    this.searchSendStatusList();
    this.searchConfirmStatusList();
    this.searchCheckStatusList();
  },
  activated() {
    // console.log(this.$route.params);
    // 如果路由有传参，刷新请求列表数据
    if (this.$route.query && JSON.stringify(this.$route.query) != '{}') {
      this.routeData = this.$route.query;
      const { id, wagesId, companyId, subId } = this.routeData;
      console.log(this.$route.query);
      this.listQuery = {
        ...this.listQuery,
        payslipId: id,
        wagesId,
        companyId,
        subId
      };
    }
    this.handleSearchDetailstList(true);
  }
};
</script>
<style lang="less" scoped>
#electronicPayslipDetails {
  // min-width: 1040px;
  .detailsHeader {
    line-height: 40px;
    border-bottom: 1px solid #dcdfe6;
    margin-bottom: 10px;
    span {
      margin-right: 20px;
    }
    .title {
      font-weight: 700;
      font-size: 18px;
    }
  }
  .pageHead {
    display: flex;
    justify-content: space-between;
  }
  .listQueryForm {
    :deep(.el-form-item) {
      .el-select {
        width: 90px;
      }
    }
  }
  .pageMain {
    height: calc(100% - 100px) !important;
    .tableContent {
      position: relative;
      padding: 0;
      height: 100%;
      // height: calc(100% - 40px);
    }
  }
  .pagingChild {
    float: right;
    margin-right: 10px;
    margin-top: 5px;
    .el-pagination__total {
      line-height: 28px;
    }
  }
  .rightBox {
    align-items: center;
    display: flex;
    flex-wrap: nowrap;
  }
}
</style>
